const useStorage = ($storage:any) => {
    const get = (key: string) => {
      let value = $storage.getItem(key);
      try {
        value = JSON.parse(value);
            return value;
        } catch {
            return value;
        }
    }

    const set = (key: string, value: any) => {
        
        return $storage.setItem(key, value ? JSON.stringify(value) : value);
    }

    const remove = (key: string) => {
        return $storage.removeItem(key);
    }

    const clearExcept = (key: string) => {
        for (let i = 0; i < $storage.length; i++) {
            const itemKey: string | undefined = $storage.key(i);
            if (itemKey && itemKey !== key) {
                $storage.removeItem(itemKey);
            }
        }
    }

    const clearAll = () => {
        for (const itemKey in $storage) {
            if (itemKey) {
                $storage.removeItem(itemKey);
            }
        }
    }

    return {
        get,
        set,
        remove,
        clearExcept,
        clearAll,
    }
}

const SessionStorageService = useStorage(window.sessionStorage || sessionStorage)
const LocalStorageService = useStorage(window.localStorage || localStorage)

export {
    SessionStorageService,
    LocalStorageService,
}